<?php

namespace weChat;


use custom\Curl;
use custom\Err;
use custom\Log;
use think\Exception;

class OfficialAccount {

    protected static $config = [
        'appid'      => 'wxa486c666ae6fbb8a', //应用唯一标识，在微信开放平台提交应用审核通过后获得
        'secret'     => 'fef538b98ec331a6f2d426c95378bb63', //应用密钥 AppSecret，在微信开放平台提交应用审核通过后获得
        'grant_type' => 'client_credential', //填 client_credential
    ];

    public static function getAccessToken() {
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $urlData['appid'] = static::$config['appid'];
        $urlData['secret'] = static::$config['secret'];
        $urlData['grant_type'] = static::$config['grant_type'];
        $url .= "?" . http_build_query($urlData);
        static::request($url);
    }

    public static function sendTemplateMessage($accessToken) {
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}";
        $data = [
            'touser' => 'OPENID',
            'template_id' => 'AakmXB06VqHROmfxIWXMmsGHYAGthWtAyz-_V6V7nR4',
            'url' => '',
            'data' => [
                'first' => [
                    'value' => '尊敬的用户，有客户访问你的项目！'
                ],
                'keyword1' => [
                    'value' => '张某某'
                ],
                'keyword2' => [
                    'value' => '某某项目'
                ],
                'keyword3' => [
                    'value' => '某某资源'
                ],
                'remark' => [
                    'value' => 'xxx'
                ],
            ],
        ];
        static::request($url, $data, "POST");
    }

    /**
     * 微信公众号
     * @param $url
     * @param array $data
     * @param string $mth
     * @return bool
     * @throws Exception
     */
    public static function request($url, $data = [], $mth = 'GET') {
//        $conf = self::$configs;
//        $url = $conf['url'] . $url . (strpos($url, '?') ? '&' : '?') . "ret_coordtype={$conf['type']}&ak={$conf['ak']}&output=json";
        $res = Curl::getInstance()->xhr($mth, $url, $data);
        print_r($res);
//        Log::write("map|$url|" . json_encode($data) . '|res:' . json_encode($res), 'baidu_map.log');
//        if (empty($res)) {
//            Err::add('地图获取失败');
//            return false;
//        }
//        $res = json_decode($res, true);
//        if (!isset($res['status'])) {
//            Err::add('地图获取失败');
//            return false;
//        }
//        if ($res['status'] != 0) {
//            Err::add('地图获取失败');
//            return false;
//        }

        return $res;
    }
}